<?php


namespace Frieza\Modules\RiskContent\Controllers;

use Admin\Model\MemberModel;
use Admin\Service\Frequency;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel;
use Common\Lib\Img\ImageSrcBuild;
use Doraemon\cache\Forbid;
use Doraemon\model\AdmUserType;
use Doraemon\model\Member;
use Doraemon\model\Phone;
use Doraemon\model\RiskContent\RiskContent;
use Doraemon\service\Member\PhoneCrypto;
use Doraemon\service\RiskContent\DeviceList;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Layout\Content;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid\Displayers\DropdownActions;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Table;
use Encore\Admin\Grid\Displayers\ContextMenuActions;
use Doraemon\service\RiskContent\RiskContentInfo;
use Frieza\Modules\RiskContent\Actions\AddUserB1;
use Frieza\Modules\RiskContent\Actions\CancelForbidden;
use Frieza\Modules\RiskContent\Actions\CancelFrozen;
use Frieza\Modules\RiskContent\Actions\ForbiddenUser;
use Frieza\Modules\RiskContent\Actions\Frozen;
use Illuminate\Http\Request;

class RiskContentListController extends Controller
{

    const PAGE_SIZE = 20;
    public function index(Request $request, Content $content)
    {
        $page = $request->input("page", 1);
        $pageSize = $request->input("per_page", self::PAGE_SIZE);
        $requestData = $request->all();
        $where = [];
        $start = ($page-1)*$pageSize;

        $memberModel = new Member();
        if (isset($requestData['Find_group']) && is_numeric($requestData['Find_group']) && isset($requestData['Find']) && $requestData['Find']){
            if ($requestData['Find_group'] == 0){
                $uid = $requestData['Find'];
            }elseif ($requestData['Find_group'] == 1){
                $nick = $requestData['Find'];
            }
        }
        if (empty($requestData['edittime']["start"]) && empty($requestData['edittime']["end"])) {
            $startTime = strtotime(date('Y-m-d',time()));
            $endTime = strtotime(date('Y-m-d',time()+86400));
            $where["edittime[<>]"] = [$startTime,$endTime];
        }
        if (!empty($requestData['edittime']["start"]) && !empty($requestData['edittime']["end"])){
            $where["edittime[<>]"] = [strtotime($requestData['edittime']["start"]), strtotime($requestData['edittime']["end"])];
        }

        if (!empty($uid)) {
            $where['uid'] = $uid;
        }
        if (!empty($nick)) {
            $uid = $memberModel->getUidByNick($nick);
            if (!empty($uid)) {
                $where['uid'] = $uid;
            }
        }
        $where['ORDER'] = ['edittime' => 'DESC'];
        $where['LIMIT'] = [$start, $pageSize];
//        print_r($where);die;
        $resList = [];
        $res = RiskContent::getRiskContentListByWhere('*',$where);
        if (!empty($res)) {
            foreach ($res as $k => $v) {
                $resList[$k]['id'] = $v['uid'];
                $resList[$k]['uid'] = $v['uid'];
                $resList[$k]['edittime'] = $v['edittime'];
            }
        }
        $uids = array_column($resList ,'uid');
        $admUserTypeModel = new AdmUserType();
        if($uids && is_array($uids)){
            $batchUserInfo =  $memberModel ->getUserInfos($uids);
            $batchUserType = $admUserTypeModel -> getByUids($uids, ['uid', 'quality', 'identity_mark']);
        }
        $info = [];
        if (!empty($batchUserInfo)) {
            foreach ($batchUserInfo as $k => $v) {
                $info[$v['uid']] = $v;
            }
        }
        unset($where['ORDER']);
        unset($where['LIMIT']);
        $count = RiskContent::getRiskContentCountByWhere($where);
        $gridModel = new GridDataModel($resList, $count, ['perPage' => $pageSize]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel, $info, $batchUserType) {
                $grid->filter(function (\Encore\Admin\Grid\Filter $filter) {
                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();
                    $filter->column(1/2, function ($filter) {
                        $filter->group('Find', function ($group) {
                            $group->equal('uid');
                            $group->equal('昵称');
                        });
                    });
                    $filter->column(1 / 3, function (\Encore\Admin\Grid\Filter $filter) {

                        $filter->dropDown('edittime', [
                            'edittime' => '时间'
                        ])->betweenDatetime();
                        //时间筛选
//                        $filter->between('edittime', '时间')->datetime()->condition(['end_show_time' => \Illuminate\Support\Facades\Request::input('edittime')]);
                    });
                });
                $grid->disableExport();
                $grid->expandFilter();
                $grid->disableCreateButton();
                //$grid->disableActions();
                $grid->setActionClass(DropdownActions::class);
                //$grid->setActionClass(ContextMenuActions::class);
                $grid->disableRowSelector();
                $grid->perPages([10, 20, 30, 40, 50, 100]);
                $grid->column('avatar', '头像')->display(function(){
                    $img = RiskContentInfo::getAvatar($this->uid);
                    return '<img src = "'.$img.'" width = 45px height = 45px />';
                });
                $grid->column('uid', 'uid')->sortable();
                $grid->column("nick", "昵称")->display(function() use($info) {
                    $baseInfo = $info[$this->uid];
                    $nick = empty($baseInfo['nick']) ? '暂无' : $baseInfo['nick'];
                    return "<a href='/admin/user/Detail/$this->uid' target='_blank' >" . $nick . "</a>";
                });
//                $grid->column("device", "设备下所有账号")->modal('设备下所有账号', function () {
//                    $deviceList = DeviceList::getDeviceList($this->uid);
//                    return new Table(['uid', '昵称','头像','性别','身份'], $deviceList);
//                });
                $grid->column("device", "设备下所有账号")->display(function() {
                    return "<a href='/admin/RiskContent/deviceList?uid=$this->uid' target='_blank' >点击查看</a>";
                });
                $grid->column("addtime", "注册时间")->display(function() use($info) {
                    $baseInfo = $info[$this->uid];
                    return date("Y-m-d H:i:s", $baseInfo['addtime']);
                });
                $grid->column("edittime", "违规时间")->display(function() {
                    return date("Y-m-d H:i:s", $this->edittime);
                });
                $grid->column("quality", "用户当前等级和状态")->display(function() use($batchUserType) {
                    $baseInfo = $batchUserType[$this->uid];
                    //用户身份
                    if ($baseInfo['quality'] == 0) {
                        $quality = "正常";
                    } elseif ($baseInfo['quality'] == 10) {
                        $quality = "B1";
                    } elseif ($baseInfo['quality'] == 9) {
                        $quality = "B2";
                    } elseif ($baseInfo['quality'] == 11) {
                        $quality = "B3";
                    }
                    //是否禁言
                    $isForbid = RiskContentInfo::isForbid($this->uid);
                    if ($isForbid == 1) {
                        $forbidInfo = "禁言操作：[禁言中]";
                        $removeOptions = "<button class='btn remove-forbidden btn-success' data-uid='$this->uid' data-time='86400'>"."解除禁言"."</button>";
                        return "用户身份:{$quality}<br/><br/>"."$forbidInfo"."<br/><br/>".$removeOptions;
                    } else {
                        $forbidInfo = "禁言操作：[正常]";
                        $optionsOne = "<button class='btn forbidden btn-primary' data-uid='$this->uid' data-time='86400'>"."禁言1天"."</button>";
                        $optionsThree = "<button class='btn forbidden btn-primary' data-uid='$this->uid' data-time='259200' >"."禁言3天"."</button>";
                        $optionsSeven = "<button class='btn forbidden btn-primary' data-uid='$this->uid' data-time='604800' >"."禁言7天"."</button>";
                        $optionsThirty = "<button class='btn forbidden btn-primary' data-uid='$this->uid' data-time='2592000' >"."禁言30天"."</button>";
                        return "用户身份:{$quality}<br/><br/>"."$forbidInfo"."<br/><br/>".$optionsOne.$optionsThree.$optionsSeven.$optionsThirty;
                    }



//                    return "用户身份:{$quality}<br/>".$forbidInfo."<br/>".$options_one;

                });
                $grid->column("forbidInfo", "禁言记录(最近3条)")->display(function() use($batchUserType) {
                    $forbidInfo = RiskContentInfo::getForbidLog($this->uid,3);
                    $info = '';
                    if (!empty($forbidInfo)) {
                        foreach ($forbidInfo as $k =>$val) {
                            $date = date("Y-m-d H:i:s",$val['addtime']);
                            if ($val['forbid_seconds'] < 86400) {  //小于一天的按分钟算
                                $forbidTime = intval($val['forbid_seconds']/60)."分钟";
                            } else {
                                $forbidTime = intval($val['forbid_seconds']/86400)."天";
                            }
                            $info .= "$date 禁言时间为：$forbidTime<br/>";
                        }
                    }
                    return $info;
                });
                $grid->column("comment", "最近五条评论")->display(function() {
                    $comment = RiskContentInfo::getComment($this->uid);
                    $info = '';
                    if (!empty($comment)) {
                        foreach ($comment as $k => $v) {
                            $objId = $v['obj_id'];
                            $info .= "【内容id】：<a href='/admin/comment/index?search[obj_id]=$objId' target='_blank' >" . $v['obj_id'] . "</a><br/>【内容】：".$v['comment']."<br/>";
                        }
                        $info .= "<br><a href='/admin/comment/index?search[uid]=$this->uid' target='_blank'>查看所有评论</a>";
                    }
                    return $info;
                })->width(500);
                $grid->actions(function (Grid\Displayers\Actions $actions) use ($info) {
                    $uid = $this->row->id;
                    $actions->disableView();
                    $actions->disableEdit();
                    $actions->disableDelete();
//                    $actions->append('<a class="fa reloadJoin" data-o_status="4" data-id="'.$this->uid.'" href="javascript:;">加入B1</a>');
                    $actions->add(new AddUserB1());
                    $userInfo = $info[$uid];
                    if (!empty($userInfo['status']) && $userInfo['status'] == Member::STATUS_BLOCKED){
                        $actions->add(new CancelForbidden());
                    } else {
                        $actions->add(new ForbiddenUser());
                    }

                    if (!empty($userInfo['status']) && $userInfo['status'] == Member::STATUS_FROZEN){
                        $actions->add(new CancelFrozen());
                    } else {
                        $actions->add(new Frozen());
                    }

//                    $actions->append('<a class=\'btn order_refresh btn-xs btn-success fa grid-check-row\' data-id="'.$this->uid.'">冻结</a>');
                });
            });
        Admin::script($this->forbiddenSpeech());
        Admin::script($this->freeForbidden());

        return $content
            ->header('用户违规查询')
            ->description(' ')
            ->breadcrumb(['text' => '用户违规查询'])
            ->row($gridList);

    }

    public function deviceList(Request $request, Content $content)
    {
        $requestData = $request->all();
        $uid = $requestData['uid'];
        $deviceList = DeviceList::getDeviceList($uid);
        $count = count($deviceList);
        $gridModel = new GridDataModel($deviceList, $count, ['perPage' => 20]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->disableExport();
                $grid->disableCreateButton();
                $grid->disableFilter();
                $grid->disableActions();
                $grid->disablePagination();
                $grid->disableRowSelector();
                $grid->column('uid', 'uid')->sortable();
                $grid->column('nick', '昵称');
                $grid->column('avatar', '头像')->display(function(){
                    return '<img src = "'.$this->avatar.'" width = 45px height = 45px />';
                });
                $grid->column('gender', '性别');
                $grid->column('type', '身份');
            });

        return $content
            ->header('设备下所有账号')
            ->description(' ')
            ->breadcrumb(['text' => '设备下所有账号'])
            ->row($gridList);



    }

    public function forbiddenSpeech()
    {
        $url = route('rickContent.addForbidden');
        return <<<EOF
            $('.forbidden').on('click', function() {
            var uid = $(this).data('uid');
            var time = $(this).data('time');

            swal({
                title: "确认禁言该用户吗？",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {
                    $.post('{$url}', {uid:uid,time:time}, function(result) {
                        if(result.code == 1) {
                            toastr.success(result.msg, null, {
                                timeOut : 1000
                            });   
                                                $.admin.reload();
                
                        } else {
                            toastr.error(result.msg, null, {
                                timeOut : 1000
                            }); 
                                                $.admin.reload();
                        }   
                    });
                }
            });
        });
EOF;
    }

    public function freeForbidden()
    {
        $url = route('rickContent.freeForbid');
        return <<<EOF
            $('.remove-forbidden').on('click', function() {
            var uid = $(this).data('uid');

            swal({
                title: "确定解禁该用户吗？",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {
                    $.post('{$url}', {uid:uid}, function(result) {
                        if(result.code == 1) {
                            toastr.success(result.msg, null, {
                                timeOut : 1000
                            });   
                                                $.admin.reload();
                
                        } else {
                            toastr.error(result.msg, null, {
                                timeOut : 1000
                            }); 
                                                $.admin.reload();
                        }   
                    });
                }
            });
        });
EOF;
    }


}